﻿using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YJ_App.Admin_System.Interface;
using YJ_App.Login.Interface;
using YJ_App.Tool.GenerateId;
using YJ_Code.Entities.User;
using YJ_Code.Enums;
using YJ_Code.Tool;
using YJ_Core.Entities.User;
using YJ_Core.Entities.Utils;
using static YJ_App.Admin_System.Dtos.UserAdminDto;

namespace YJ_App.Admin_System.Service
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.UserAdmin, Name = "UserAdmin")]
    public class UserAdmin : IDynamicApiController, ITransient, IUserAdmin
    {
        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public UserAdmin(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SelectUserListResp> SelectUserList(SelectUserListInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);
            RefAsync<int> total = 0;

            var list = await _db.Queryable<UserInfo>()
                .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKeyword),
                (t1) => t1.Email.Contains(input.SearchKeyword)
                || t1.NickName.Contains(input.SearchKeyword)
                || t1.UserName.Contains(input.SearchKeyword)
                || t1.UserId.Contains(input.SearchKeyword))
                .WhereIF(input.StartDate.HasValue && input.EndDate.HasValue,
                (t1) => t1.CreateTime >= input.StartDate && t1.CreateTime < input.EndDate)
                .Select((t1) => new SelectUserListOutput
                {
                    Email = t1.Email,
                    State = t1.State,
                    UserId = t1.UserId,
                    UserName = t1.UserName,
                    NickName = t1.NickName,
                    CreateTime = t1.CreateTime,
                    HeadPortraitPath = t1.HeadPortraitPath,
                })
                .OrderByDescending(t => t.CreateTime)
                .ToPageListAsync(input.Page, input.PageSize, total);

            return new SelectUserListResp
            {
                Total = total,
                List = list,
                Message = "请求成功",
                StatusCode = 200
            };
        }

        /// <summary>
        /// 修改用户状态（禁用/启用）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseStatus> UpdateUserState(UpdateUserStateInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);
            var user = await _db.Queryable<UserInfo>()
                .FirstAsync(it => it.UserId == input.UserId) ?? throw Oops.Bah("用户信息有误");

            user.State = input.State;

            int count = await _db.Updateable(user)
                .WhereColumns(it => it.UserId)
                .UpdateColumns(it => it.State).ExecuteCommandAsync();
            if (count < 1)
            {
                throw Oops.Bah("状态设置失败");
            }

            return new ResponseStatus { Message = "设置成功", StatusCode = 200 };
        }

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseStatus> UpdateUserInfo(UpdateUserInfoInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            var user = await _db.Queryable<UserInfo>()
                .FirstAsync(it => it.UserId == input.UserId) ?? throw Oops.Bah("用户信息有误");
            user.State = input.State;
            user.UserName = input.Account;
            user.Email = input.Email;
            user.NickName = input.NickName;
            user.UpdateMan = input.Email;
            user.UpdateTime = DateTime.Now;

            int count = await _db.Updateable(user)
                .WhereColumns(it => it.UserId)
                .UpdateColumns(it => new
                {
                    it.NickName,
                    it.State,
                    it.UserName,
                    it.Email,
                    it.UpdateMan,
                    it.UpdateTime,
                }).ExecuteCommandAsync();
            if (count < 1)
            {
                throw Oops.Bah("编辑失败");
            }
            return new ResponseStatus { Message = "编辑成功", StatusCode = 200 };
        }
    }
}
